import React, { useState, useRef, useEffect } from "react";
import "./SearchDropdown.css";

const TABS = [
  { key: "template", label: "模板" },
  { key: "material", label: "素材" },
  { key: "my", label: "我的设计" },
];

// 假数据
const SUGGESTS = [
  "大暑海报",
  "早安问候",
  "喜报模板",
  "邀请函设计",
  "小红书封面",
  "PPT16:9",
  "简历模板",
  "公众号首图",
  "商品主图",
  "长图海报"
];

function highlightKeyword(text: string, keyword: string) {
  if (!keyword) return text;
  const parts = text.split(new RegExp(`(${keyword})`, "gi"));
  return (
    <>
      {parts.map((part, i) =>
        part.toLowerCase() === keyword.toLowerCase() ? (
          <span key={i} style={{ color: "#1677ff", fontWeight: 700 }}>{part}</span>
        ) : (
          part
        )
      )}
    </>
  );
}

const HOT_SEARCH = [
  { label: '大暑', color: 'linear-gradient(90deg, #FF7F50 0%, #FFB86C 100%)' },
  { label: '早安', color: 'linear-gradient(90deg, #FFB800 0%, #FFD36C 100%)' },
  { label: '海报', color: 'linear-gradient(90deg, #FFC300 0%, #FFD36C 100%)' },
  { label: '报纸', color: '#E5E6EB' },
  { label: '简历', color: '#E5E6EB' },
  { label: '邀请函', color: '#E5E6EB' },
];
const SCENE_SEARCH = [
  '手机海报', '全屏海报', '小红书配图', '公众号首图', '每日一签', '邀请函', '长图海报', 'PPT16:9',
  '主图图标', '商品主图', '名片', '长页H5', '竖版直播', '直播贴片', '视频海报', '横版海报', '宣传单', '竖版插画', '公众号次图', '简历'
];

const SearchDropdown = ({
  visible,
  onClose,
  value
}: {
  visible: boolean;
  onClose: () => void;
  value: string;
}) => {
  const [activeTab, setActiveTab] = useState("template");
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        onClose();
      }
    }
    if (visible) document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, [visible, onClose]);

  if (!visible) return null;

  // 联想结果
  const filtered = value
    ? SUGGESTS.filter(item => item.toLowerCase().includes(value.toLowerCase()))
    : [];

  return (
    <div className="search-dropdown" ref={ref}>
      <div className="search-tabs">
        {TABS.map(tab => (
          <div
            key={tab.key}
            className={`search-tab${activeTab === tab.key ? " active" : ""}`}
            onClick={() => setActiveTab(tab.key)}
          >
            {tab.label}
          </div>
        ))}
      </div>
      <div className="search-tab-content">
        {activeTab === "template" && (
          <div className="template-tab-panel">
            <div className="hot-search-title">热门搜索</div>
            <div className="hot-search-list">
              {HOT_SEARCH.map((item, idx) => (
                <div className="hot-search-item" key={item.label}>
                  <span className="hot-search-index" style={{ background: item.color }}>{idx + 1}</span>
                  <span className="hot-search-label">{item.label}</span>
                </div>
              ))}
            </div>
            <div className="scene-search-title">按场景搜索</div>
            <div className="scene-search-list">
              {SCENE_SEARCH.map((item, idx) => (
                <span className="scene-search-item" key={item}>{item}</span>
              ))}
              <span className="scene-search-more">全部场景 &gt;</span>
            </div>
          </div>
        )}
        {activeTab === "material" && <div>素材内容区（如分类、推荐等）</div>}
        {activeTab === "my" && <div>我的设计内容区（如最近设计等）</div>}
      </div>
      {value && (
        <div className="search-suggest-list">
          {filtered.length === 0 ? (
            <div className="search-suggest-empty">无匹配结果</div>
          ) : (
            filtered.map((item, idx) => (
              <div className="search-suggest-item" key={idx}>
                {highlightKeyword(item, value)}
              </div>
            ))
          )}
        </div>
      )}
    </div>
  );
};

export default SearchDropdown; 